export { playAudio, stopAudio, inputVolume, heartCheck, heartCheckTest };

function playAudio(objSocket, player, timeoutObj) {
  initSocket(objSocket, player, timeoutObj);
  console.log("点击事件--播放音频" + player);
}

function stopAudio(objSocket) {
  objSocket.send("close");
  objSocket.close(1000, "Disconnect");
  console.log("点击事件--停止播放");
}

function initSocket(objSocket, player, timeoutObj) {
  // var url_pass = sessionStorage.getItem("url_pass");
  //const url = "ws://" + window.location.hostname + "/audio_stream";
  // const url = "ws://192.168.2.168/audio_stream";
  // var url_pass = "ws://192.168.2.168:8000";

  // WebSocket服务连接
  // objSocket = new WebSocket(url_pass);
  objSocket.onopen = function () {
    onOpen(objSocket, timeoutObj);
  };
  objSocket.onclose = function () {
    onClose(timeoutObj);
  };
  objSocket.onmessage = function (evt) {
    onMessage(evt, player);
  };
  objSocket.onerror = function (evt) {
    onError(evt, timeoutObj);
  };
}

function onOpen(objSocket) {
  heartCheck(objSocket);
  console.log("Connected to WebSocket server");
}

function onClose(timeoutObj) {
  clearTimeout(timeoutObj);
  console.log("Disconnected");
}

function onError(evt, timeoutObj) {
  clearTimeout(timeoutObj);
  console.log("Error ocured: " + evt.data);
}

function onMessage(evt, player) {
  //websocket返回数据信息处理
  var reader = new FileReader(); //文件阅读器
  reader.readAsArrayBuffer(evt.data); //读取成ArrayBuffer对象
  reader.onload = function () {
    //读取完毕
    // Now feed PCM data into player getting from websocket or ajax whatever the transport you are using.Accept ArrayBuffer or TypedArray
    // 接收PCM格式的原始数据，ArrayBuffer 类型或者 TypedArray 类型
    player.feed(this.result);
  };
}

function inputVolume(player, voice) {
  player.volume(Number(voice));
}

//心跳检测
function heartCheck(objSocket, timeoutObj) {
  objSocket.send("ping");
  timeoutObj = setTimeout("heartCheck(objSocket,timeoutObj)", 50000);
}

function heartCheckTest(objSocket, timeoutObj) {
  objSocket.send("ping");
  timeoutObj = setTimeout("heartCheckTest(objSocket,timeoutObj)", 10000);
}
